package com.jinsi.service.yrf.iml;

import com.jinsi.pojo.SyUser;
import com.jinsi.pojo.Role;
import com.jinsi.pojo.UserRole;
import com.jinsi.service.yrf.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 安全框架获取账号密码信息
  * 吕昊燃
  * @Date 2022/10/12
 */
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    public static  SyUser syUser;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        // 从数据库中取出用户信息
        SyUser user = userService.getUserByNameAndPwd(username);
        syUser =user;
        // 判断用户是否存在
        if(user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
//        if(user.getSealState() == 0) {
//            throw new UsernameNotFoundException("账号正在封禁中");
//        }

        // 添加权限
        List<UserRole> userRoles = userService.listByUserId(user.getUserId());
        for (UserRole userRole : userRoles) {
            Role role = userService.selectById(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        // 返回UserDetails实现类
        return new User(user.getUserName(), user.getUserPwd(), authorities);
    }
}
